#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#include "api/api.h"

int main(int argc, char *argv[])
{
	#if DEBUG >= 1
	printf("########## RECEIVER BEGINS ##########\n");
	#endif
	
	if( argc < 2 ) {
		printf("ERROR: WRONG ARGUMENT NUMBER\nusage: receiver <serial_port>\n");
		exit(-EXIT_FAILURE);
	}
	else if( argc >= 3 ) {
		baudrate = atoi(argv[2]);
	}
	
	int port_path;
	const char *portS0 = TTYS0_VALUE;
	const char *portS1 = TTYS1_VALUE;
	
	if( !strcmp(portS0, argv[1]) )
		port_path = TTYS0;
	else if ( !strcmp(portS1, argv[1]) )
		port_path = TTYS1;
	else {
		printf("ERROR: WRONG SERIAL PORT PATH.\nPlease try \"%s\" or \"%s\"\n", portS0, portS1);
		exit(-EXIT_FAILURE);
	}
		
	int port_fd;
	
	if( (port_fd = llopen(port_path, RECEIVER)) < 0 ) {
		printf("ERROR: LLOPEN FAILED.\n Return value: %d\n", port_fd);
		exit(-EXIT_FAILURE);
	}
	
	#if DEBUG >= 1
	printf("\n>>>>> Connection setup done <<<<<\n\n");
	#endif
	
	
	char buf[DATA_SIZE];
	int total_frames = 0;
	int total_bytes = 0;
	int bytes_read = -1;
	
	llread(port_fd, buf);
	char filepath[DATA_SIZE] = "output/";
	
	strcat(filepath, buf);
	
	int file_fd = open(filepath, O_WRONLY | O_CREAT, 0740);
	
	while(bytes_read != 0)
	{
		bzero(buf,DATA_SIZE);
		bytes_read = llread(port_fd, buf);
		if (bytes_read == 0) //received final packet with no data
		{
			break;
		}
		else
		{
			write(file_fd, buf, bytes_read);
			total_bytes += bytes_read;
			total_frames++;
			printf("framecounter = %d; byte counter = %d\n", total_frames, total_bytes);
		}
	}
	
	printf("TOTAL BYTES RECEIVED: %d\n", total_bytes);
	
	close(file_fd);
	
	llclose(port_fd);
	
	return 0;
}
